<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace plugins\blog\api\controller;

use think\exception\ValidateException;
use app\api\BaseController;
use plugins\blog\api\validate\Comment as Validate;
use plugins\blog\api\model\BlogComment as BlogCommentModel;
/**
 * 文章评论
 */
class BlogComment extends BaseController
{
    /**
     * 评论列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            try {
                $input = input('post.');
                validate(Validate::class)->scene('index')->check($input);
            } catch ( ValidateException $e ) {
                return json(['status' => 'error', 'message' => $e->getError()]);
            }
            $where[] = ['blog_id', '=', $input['id']];
            $where[] = ['pid', '=', 0];
            $append = ['like','is_like', 'loading', 'friend_time'];
            $order = ['create_time' => 'desc'];
            $count = BlogCommentModel::where($where)->count();
            $data  = BlogCommentModel::where($where)->with(['user'])->append($append)->order($order)->page($input['page'],10)->select()->toArray();
            foreach ($data as $key => $val) {
                $data[$key]['reply'] = BlogCommentModel::where('pid', $val['id'])->with(['user','reply_user'])->append($append)->order($order)->limit(2)->select();
                $data[$key]['reply_count'] = BlogCommentModel::where('pid', $val['id'])->count();
            }
            return json(['status' => 'success', 'message' => '获取成功', 'data' => $data, 'count' => $count]);
        }
    }
    
    /**
     * 回复列表
     */
    public function reply()
    {
        if ($this->request->isPost()) {
            try {
                $input = input('post.');
                validate(Validate::class)->scene('reply')->check($input);
            } catch ( ValidateException $e ) {
                return json(['status' => 'error', 'message' => $e->getError()]);
            }
            $count = BlogCommentModel::where('pid', $input['id'])->count();
            $data  = BlogCommentModel::where('pid', $input['id'])
            ->with(['user','reply_user'])
            ->append(['like','is_like','loading', 'friend_time'])
            ->order('create_time', 'desc')
            ->page($input['page'],10)
            ->select();
            return json(['status' => 'success', 'message' => '获取成功', 'data' => $data, 'count' => $count]);
        }
    }
}